<template>
  <div>
    <!--  设置默认地址  -->
    <el-dialog
        title="地址簿"
        :visible.sync="dialogAddressVisible"
        width="50%"
        :show-close="false"
        :modal-append-to-body="false"
        @open="handleOpen"
        @close="handleClose">
      <el-form
          :model="addressForm"
          ref="addressForm"
          style="height: 400px; display: flex; flex-direction: column; justify-content: space-between;">
        <label style="margin-bottom: 35px">设置默认地址</label>
        <el-radio-group
            v-model="id"
            size="small"
            style="margin-top: -10px">
          <el-radio
              v-for="address in addressList"
              :key="address.id"
              :label="address.id"
              :value="address.id"
              style="display: flex; flex-direction: row;margin-bottom: 20px">
            {{ address.address }}
          </el-radio>
        </el-radio-group>
        <el-form-item>
          <el-button
              type="text"
              @click="dialogInsertVisible = true">
            +添加地址
          </el-button>
          <el-button
              type="text"
              class="blueBug"
              @click="update()">
            修改地址
          </el-button>
          <el-button
              type="text"
              class="redBug"
              @click="deleteAddress()">
            删除地址
          </el-button>
        </el-form-item>
        <el-form-item style="margin-top: auto">
          <el-button type="primary" @click="submitForm('addressForm')">保存</el-button>
          <el-button @click="dialogAddressVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!--  新增地址  -->
    <el-dialog
        title="添加地址"
        :visible.sync="dialogInsertVisible"
        width="25%"
        :show-close="false"
        :modal-append-to-body="false"
        @close="handleCloseInsert">
      <el-form
          :model="insertForm"
          :rules="rules"
          style="height: 400px"
          ref="insertForm"
          label-width="100px"
          class="demo-ruleForm">
        <el-form-item label="收件人" prop="consignee">
          <el-input
              placeholder="请输入姓名"
              v-model="insertForm.consignee">
            <i slot="suffix"
               style="margin-top: 8px;font-size: 18px;"/>
          </el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input
              placeholder="请输入手机号"
              v-model="insertForm.phone">
            <i slot="suffix"
               style="margin-top: 8px;font-size: 18px;"/>
          </el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio v-model="insertForm.sex" label="0">男</el-radio>
          <el-radio v-model="insertForm.sex" label="1">女</el-radio>
        </el-form-item>
        <el-form-item>
          <i class="iconfont icon-icon-test20" style="margin-right: 10px"/>
          <el-cascader
              size="large"
              :options="regionData"
              v-model="selectedOptionsCode"
              placeholder="请选择地址">
          </el-cascader>
        </el-form-item>
        <el-form-item label="详细地址:">
          <el-input
              placeholder="请输入详细地址信息"
              v-model="insertForm.detail">
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('insertForm')">保存</el-button>
          <el-button @click="dialogInsertVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>

</template>

<script lang="ts">
import {Component, Vue} from 'vue-property-decorator';
import UploadImage from "@/components/ImgUpload/index.vue";
import {codeToText, regionData} from "element-china-area-data";
import {Form} from "element-ui";
import {deleteAddressById, getAddressById, getAddressList, getDefault, insertAddress, setDefault} from "@/api/address";

@Component({
  name: 'AddressInfo',
  components: {UploadImage},
})
export default class index extends Vue {
  private dialogAddressVisible = false;
  private dialogInsertVisible = false;
  private regionData = regionData;
  private selectedOptionsCode: any[] = [];
  private selectedOptionsText: any[] = [];
  private addressList: any[] = [];
  private id :any = '';

  private addressForm = {
    id: '',
  } as {
    id: string;
  }

  private insertForm = {
    consignee: '',  // 收货人
    provinceCode: '',  // 省
    provinceName: '',
    cityCode: '',  // 市
    cityName: '',
    districtCode: '',   // 区
    districtName: '',
    phone: '',
    sex: '0',
    detail: '',
  } as {
    detail: string;
    consignee: string;
    provinceCode: string;
    provinceName: string;
    cityCode: string;
    cityName: string;
    districtCode: string;
    districtName: string;
    phone: string;
    sex: string,
  }

  rules = {
    consignee: [
      {
        required: true, trigger: 'blur', validator: (rule, value, callback) => {
          if (!value) {
            callback(new Error('请输入用户名'))
          } else {
            callback();
          }
        }
      }
    ],
    phone: [
      {
        required: true, trigger: 'blur', validator: (rule, value, callback) => {
          if (value === '' || (!/^1[3-9]\d{9}$/.test(value))) {
            callback(new Error('请输入正确的手机号'))
          } else {
            callback()
          }
        }
      }
    ],
  }

  submitForm(formName) {
    if (formName === 'insertForm') {
      this.selectedOptionsCode.forEach((item) => {
        this.selectedOptionsText.push(codeToText[item]);
      });

      const data = this.insertForm;
      data.provinceCode = this.selectedOptionsCode[0];
      data.provinceName = this.selectedOptionsText[0];
      data.cityCode = this.selectedOptionsCode[1];
      data.cityName = this.selectedOptionsText[1];
      data.districtCode = this.selectedOptionsCode[2];
      data.districtName = this.selectedOptionsText[2];

      (this.$refs.insertForm as Form).validate(valid => {
        if (valid) {
          insertAddress(data).then(res => {
            if (res.data.code === 1) {
              this.$message.success("保存成功");
              this.handleCloseInsert();
              this.getAllAddress();
            }
          }).catch(err => {
            this.$message.error(err.message);
          })
        }
      })
    } else {
      this.addressForm.id = this.id;
      localStorage.setItem('addressId',this.id)
      setDefault(this.addressForm.id).then(res => {
        if (res.data.code === 1) {
          this.$message.success("设置成功");
          this.dialogAddressVisible = false;
        }
      }).catch(err => {
        this.$message.error(err.message);
      })
    }
  }

  getAllAddress() {
    getAddressList().then(res => {
      if (res.data.code === 1) {
        let tempList: any[] = [];
        res.data.data.forEach((item) => {
          let address = `收件人: ${item.consignee}\n手机号: ${item.phone}\n地址: ${item.provinceName}
          ${item.cityName} ${item.districtName} ${item.detail}`;
          tempList.push({
            id: item.id, // 确保 id 属性存在
            address: address
          });
        })
        this.addressList = tempList;
      }
    })
  }

  getDefaultAddress() {
    getDefault().then(res => {
      if (res.data.code === 1) {
        this.id = res.data.data.id;
      }
    })
  }

  update() {
    getAddressById(this.id).then(res => {
      if (res.data.code === 1) {
        this.insertForm = res.data.data;
        this.dialogInsertVisible = true;
      }
    })
  }

  deleteAddress() {
    this.$confirm('此操作永久删除改数据, 确定吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      deleteAddressById(this.id).then(res => {
        if (res.data.code === 1) {
          this.$message.success("删除成功");
          this.addressList = this.addressList.filter(address => address.id !== this.id);
          this.id = null; // 清空选中的 ID
        } else {
          this.$message.error(res.data.msg);
        }
      }).catch(err => {
        this.$message.error(err.message);
      })
    })
  }

  handleCloseInsert() {
    this.dialogInsertVisible = false;
    this.insertForm = {
      consignee: '',  // 收货人
      provinceCode: '',  // 省
      provinceName: '',
      cityCode: '',  // 市
      cityName: '',
      districtCode: '',   // 区
      districtName: '',
      phone: '',
      sex: '1',
      detail: '',
    };

    const form = this.$refs.insertForm as Form;
    form.clearValidate();
    this.selectedOptionsCode = [];
  }

  handleOpen() {
    this.getAllAddress();
    this.getDefaultAddress();
  }

  handleClose() {
    this.dialogAddressVisible = false;

    this.addressForm = {
      id: ''
    };
    this.$emit('closed');
  }
}
</script>


<style scoped lang="scss">
.blueBug {
  color: #419EFF !important;
  position: relative;
}

.redBug {
  color: #ff0000 !important;
  position: relative;
}
</style>
